package xframe.util;

import javax.servlet.http.*;

public class CookieUtil {
    public static String encoding = "utf-8";
    public static void setCookie(HttpServletResponse response, String name, String value)throws Exception{
        value = java.net.URLEncoder.encode(value,encoding);
        javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(name, value);
        cookie.setMaxAge(60*60*24*3000);
        response.addCookie(cookie);
    }

    public static void setCookie(HttpServletResponse response, String name, String value, int age )throws Exception{
        value = java.net.URLEncoder.encode(value,encoding);
        javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(name, value);
        cookie.setMaxAge(age);
        response.addCookie(cookie);
    }
    public static void setCookie(HttpServletResponse response, String name, String value,String uri)
            throws Exception
    {
        value = java.net.URLEncoder.encode(value,encoding);
        javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(name, value);
        cookie.setPath(uri);
        cookie.setMaxAge(60*60*24*3000);
        response.addCookie(cookie);
    }

    public static String getCookie(HttpServletRequest request, String cookieName)throws Exception{
        javax.servlet.http.Cookie [] cookies = request.getCookies();
        String value = null;
        if(cookies != null){
            for(int i=0;i<cookies.length;i++) {
                if(cookieName.equals(cookies[i].getName())) {
                    value = java.net.URLDecoder.decode(cookies[i].getValue(),encoding);
                    break;
                }
            }
        }
        return value;
    }

    public static void delCookie(HttpServletRequest request, String cookieName)throws Exception{
        javax.servlet.http.Cookie [] cookies = request.getCookies();
        for(int i=0; i<cookies.length; i++){
            Cookie thisCookie = cookies[i];
            if(cookieName.equals(thisCookie.getName())){
                thisCookie.setMaxAge(0); // ��Ű ��ֱ�
                thisCookie.setValue("");
                thisCookie.setPath("/");
            }
        }
    }

    public static boolean isCookie(HttpServletRequest request, String cookieName){
        javax.servlet.http.Cookie [] cookies = request.getCookies();
        if(cookies != null){
            for(int i=0;i<cookies.length;i++) {
                // System.out.println("cookie : "+cookies[i].getName()+": "+ cookies[i].getValue());
                if(cookieName.equals(cookies[i].getName())) {
                    return true;
                }
            }
        }
        return false;
    }
}

